package org.boulderfoodrescue.webapp.client.pickuptimes.timepicker;

import java.util.Date;

import org.boulderfoodrescue.webapp.client.old.event.HasViewClosedHandlers;
import org.boulderfoodrescue.webapp.client.old.event.ViewClosedEvent;
import org.boulderfoodrescue.webapp.client.old.event.ViewClosedHandler;
import org.boulderfoodrescue.webapp.client.pickuptimes.timepicker.PickupWindow.RepeatType;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.i18n.shared.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;

public class RepeatDialogPanel extends Composite implements HasViewClosedHandlers<Boolean>{

	private static RepeatDialogPanelUiBinder uiBinder = GWT
			.create(RepeatDialogPanelUiBinder.class);

	interface RepeatDialogPanelUiBinder extends
	UiBinder<Widget, RepeatDialogPanel> {
	}

	@UiField
	ListBox repeat_type;
	@UiField
	FlowPanel section_repeat_every;
	@UiField 
	ListBox repeat_options;
	@UiField
	Label repeat_text;
	@UiField
	FlowPanel section_repeat_on;
	@UiField
	CheckBox sunday;
	@UiField
	CheckBox monday;
	@UiField
	CheckBox tuesday;
	@UiField
	CheckBox wednesday;
	@UiField
	CheckBox thursday;
	@UiField
	CheckBox friday;
	@UiField
	CheckBox saturday;
	@UiField
	FlowPanel section_repeat_by;
	@UiField
	RadioButton day_of_month;
	@UiField
	RadioButton day_of_week;
	@UiField
	TextBox start_date;
	@UiField
	RadioButton ends_never;
	@UiField
	RadioButton ends_after;
	@UiField
	RadioButton ends_on;
	@UiField
	TextBox num_occurances;
	@UiField
	DateBox ends_after_date;
	@UiField
	Label summary;
	@UiField
	Button set;
	@UiField
	Button cancel;

	private EventBus bus = new SimpleEventBus();
	private PickupWindow pickupEvent;

	public RepeatDialogPanel(PickupWindow pickupEvent) {
		initWidget(uiBinder.createAndBindUi(this));
		//CloseEvent.fire(this, false);
		this.pickupEvent = pickupEvent;
		ends_after_date.setFormat(new ShortDateFormat());
		if(pickupEvent.getRepeatType() != RepeatType.None){
			loadPickupEvent();
		}
		start_date.setText(DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat
				.DATE_SHORT).format(pickupEvent.getStart_time()));
		onRepeatTypeChange(null);
	}

	@Override
	public void fireEvent(GwtEvent<?> event){
		bus.fireEvent(event);
	}

	@Override
	public HandlerRegistration addViewClosedHandler(ViewClosedHandler<Boolean> handler) {
		return bus.addHandler(ViewClosedEvent.getType(), handler);
	}

	@UiHandler ("repeat_type")
	public void onRepeatTypeChange(ChangeEvent event){
		int repeatType = repeat_type.getSelectedIndex();
		section_repeat_every.setVisible(false);
		section_repeat_on.setVisible(false);
		section_repeat_by.setVisible(false);
		switch(repeatType){
		case 0: 
			section_repeat_every.setVisible(true);
			repeat_text.setText("days");
			break;
		case 1:
			section_repeat_every.setVisible(true);
			repeat_text.setText("weeks");
			section_repeat_on.setVisible(true);
			break;
		case 2:
			section_repeat_every.setVisible(true);
			repeat_text.setText("months");
			section_repeat_by.setVisible(true);
			break;
		case 3:
			section_repeat_every.setVisible(true);
			repeat_text.setText("years");
			break;
		}
		pickupEvent.setRepeatTypeViaInt(repeatType);
		summary.setText(pickupEvent.getSummary());
	}

	@UiHandler("repeat_options")
	public void onRepeatEveryChange(ChangeEvent event){
		pickupEvent.setRepeatInterval(repeat_options.getSelectedIndex());
		summary.setText(pickupEvent.getSummary());
	}
	
	private void buildRepeatOn(int index, CheckBox box){
		StringBuilder sb = new StringBuilder(pickupEvent.getRepeatsOn());
		sb.setCharAt(index, (box.getValue()) ? '1':'0');
		pickupEvent.setRepeatsOn(sb.toString());
		summary.setText(pickupEvent.getSummary());
	}
	
	@UiHandler ("sunday")
	public void onSundayChange(ClickEvent event){
		buildRepeatOn(0, sunday);
	}

	@UiHandler ("monday")
	public void onMondayChange(ClickEvent event){
		buildRepeatOn(1, monday);
	}

	@UiHandler ("tuesday")
	public void onTuesdayChange(ClickEvent event){
		buildRepeatOn(2, tuesday);
	}

	@UiHandler ("wednesday")
	public void onWednesDayChange(ClickEvent event){
		buildRepeatOn(3, wednesday);
	}

	@UiHandler ("thursday")
	public void onThursdayChange(ClickEvent event){
		buildRepeatOn(4, thursday);
	}

	@UiHandler ("friday")
	public void onFridayChange(ClickEvent event){
		buildRepeatOn(5, friday);
	}

	@UiHandler ("saturday")
	public void onSaturdayChange(ClickEvent event){
		buildRepeatOn(6, saturday);
	}
	
	@UiHandler ("day_of_month")
	public void onDayOfMonthChange(ClickEvent event){
		pickupEvent.setRepeatBy((day_of_month.getValue())?0:1); 
		summary.setText(pickupEvent.getSummary());
	}
	
	@UiHandler ("day_of_week")
	public void onDayOfYearChange(ClickEvent event){
		pickupEvent.setRepeatBy((day_of_week.getValue())?1:0); 
		summary.setText(pickupEvent.getSummary());
	}
	
	@UiHandler ("ends_never")
	public void onEndNeverClick(ClickEvent event){
		pickupEvent.setEndType(0);
		num_occurances.setEnabled(false);
		ends_after_date.setEnabled(false);
		summary.setText(pickupEvent.getSummary());
	}
	
	@UiHandler ("ends_after")
	public void onEndAfterClick(ClickEvent event){
		pickupEvent.setEndType(1);
		num_occurances.setEnabled(true);
		ends_after_date.setEnabled(false);
		summary.setText(pickupEvent.getSummary());
	}
	
	@UiHandler ("ends_on")
	public void onEndOnClick(ClickEvent event){
		pickupEvent.setEndType(2);
		num_occurances.setEnabled(false);
		ends_after_date.setEnabled(true);
		summary.setText(pickupEvent.getSummary());
	}
	
	@UiHandler ("num_occurances")
	public void onNumOccurancesFocus(FocusEvent event){
		num_occurances.removeStyleName("dateBoxFormatError");
	}
	
	@UiHandler ("num_occurances")
	public void onNumOccurancesBlur(BlurEvent event){
		try{
			pickupEvent.setNumOccurances(Integer.parseInt(num_occurances.getText()));
		} catch(NumberFormatException e){
			num_occurances.addStyleName("dateBoxFormatError");
		}
		summary.setText(pickupEvent.getSummary());
	}
	
	@UiHandler ("ends_after_date")
	public void onEndDateChange(ValueChangeEvent<Date> event){
		pickupEvent.setEndDate(event.getValue());
		summary.setText(pickupEvent.getSummary());
	}
	
	@UiHandler ("set")
	public void onSetClick(ClickEvent event){
		pickupEvent.setRepeatTypeViaInt(repeat_type.getSelectedIndex());
		ViewClosedEvent.fire(this, true);
	}
	
	@UiHandler ("cancel")
	public void onCancelClick(ClickEvent event){
		ViewClosedEvent.fire(this, false);
	}
	
	private void loadPickupEvent(){
		int repeatType = pickupEvent.getRepeatTypeAsInt();
		repeat_type.setSelectedIndex(repeatType);
		if(repeatType==0 || repeatType==1 || repeatType == 2 || repeatType == 3){
			repeat_options.setSelectedIndex(pickupEvent.getRepeatInterval());
		}
		switch(repeatType){
		case 1:
			sunday.setValue((pickupEvent.getRepeatsOn().charAt(0)=='1'? true: false));
			monday.setValue((pickupEvent.getRepeatsOn().charAt(1)=='1'? true: false));
			tuesday.setValue((pickupEvent.getRepeatsOn().charAt(2)=='1'? true: false));
			wednesday.setValue((pickupEvent.getRepeatsOn().charAt(3)=='1'? true: false));
			thursday.setValue((pickupEvent.getRepeatsOn().charAt(4)=='1'? true: false));
			friday.setValue((pickupEvent.getRepeatsOn().charAt(5)=='1'? true: false));
			saturday.setValue((pickupEvent.getRepeatsOn().charAt(6)=='1'? true: false));
			break;
		case 2:
			day_of_month.setValue((pickupEvent.getRepeatBy()==0)? true:false);
			day_of_week.setValue((pickupEvent.getRepeatBy()==0)? false:true);
			break;
		}
		switch(pickupEvent.getEndType()){
		case 0:ends_never.setValue(true);break;
		case 1:ends_after.setValue(true);
		num_occurances.setText(pickupEvent.getNumOccurances()+"");
		num_occurances.setEnabled(true);
		break;
		case 2:ends_on.setValue(true);
		ends_after_date.setValue(pickupEvent.getEndDate());
		ends_after_date.setEnabled(true);
		}
		summary.setText(pickupEvent.getSummary());
	}
}
